package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.db.TbClubActivity;
import com.quanyan.club.entity.db.TbClubActivityExample;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.mapper.TbClubActivityMapper;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.service.ActivityCRUDService;
import com.quanyan.club.service.ActivitySupportService;
import com.quanyan.club.service.ClubActivityService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.Limit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by yue.yuan on 2016/8/12.
 */
@Component
public class ActivityCreateWeekRangeJob implements JobRunner{

    private static Logger logger = Logger.getLogger(ActivityCreateWeekRangeJob.class);

    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;

    @Autowired
    private ActivityOpenService activityOpenService;

    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private ActivityCRUDService activityCRUDService;

    @Autowired
    private TbClubMapper clubMapper;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        createWeekRangeActivity();
        return new Result(Action.EXECUTE_SUCCESS);//createWeekRangeActivity();
    }

    //@Async
    public void createWeekRangeActivity()
    {
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        TbClubActivityExample.Criteria clubCriteria = clubActivityExample.createCriteria();
        //没被删除,是日循环，且未扫描过的周期性俱乐部活动
        clubCriteria.andActivityCycleEqualTo(true)
                .andIsSearchEqualTo((byte)0)
                .andActivityStatusNotEqualTo(3f)
                .andCycleRangeIsNull()
                .andIsDeleteEqualTo((byte)0);
        int total = tbClubActivityMapper.countByExample(clubActivityExample);
        if(0 == total)
        {
            logger.warn("没有未扫描的周期性活动");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        //找出已经结束的周期性活动
        map.put("isWeek", 1L);
        Integer pageSize = 20;
        for (int i = 0; i < Math.ceil((double)total/pageSize); i++) {

            int pageNum = i + 1;
            clubActivityExample.setLimit(Limit.buildLimit(pageNum, pageSize));
            List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(clubActivityExample);
            List<Integer> ids = new ArrayList<Integer>();
            for (TbClubActivity c : clubActivities) {
                TbClub club = clubMapper.selectByPrimaryKey(c.getClubId());
                //解散俱乐部不创建周期活动
                if(club.getIsDelete().equals(Constants.BYTE_ONE))
                {
                    continue;
                }
                ids.add(c.getActivityId());
            }

            logger.warn("开始调用活动模块校验周期活动更新量，原始量：" + JSONObject.toJSONString(ids));
            Map<Integer, Integer> idMap = activityOpenService.createWeekActivity(ids, map);
            logger.warn("活动模块返回周期活动可更新量：" + JSONObject.toJSONString(idMap));
            if(null == idMap || idMap.size() == 0)
            {
                continue;
            }
            for (TbClubActivity c : clubActivities) {
                Integer newId = idMap.get(c.getActivityId());
                if(null == newId || newId == 0)
                {
                    continue;
                }
                //重置一些参数
                TbClubActivity newActivity = new TbClubActivity();
                BeanCopierUtils.copyProperties(c, newActivity);
                newActivity.setActivityStatus(0f);
                newActivity.setSignUpMin(0);
                newActivity.setActivityId(newId);
                newActivity.setIsSettle(Constants.BYTE_ZERO);
                newActivity.setIsRecommend(Constants.BYTE_ZERO);
                newActivity.setActivityRoot(newId);
                newActivity.setCreateTime(null);
                newActivity.setUpdateTime(null);
                logger.warn("开始插入一条新的俱乐部周期活动，原始活动ID：" + c.getActivityId()
                        + "新活动ID：" + idMap.get(c.getActivityId()));
                tbClubActivityMapper.insertSelective(newActivity);
                c.setIsSearch((byte) 1);
                logger.warn("更新原始俱乐部周期活动，原始活动ID：" + c.getActivityId());
                tbClubActivityMapper.updateByPrimaryKey(c);
                RespClubActivity respClubActivity = activityCRUDService.selectClubActivityById(newId);
                logger.warn("处理新活动的后续任务，新活动ID：" + newId);
                activitySupportService.afterCreateWeekRange(respClubActivity);
            }
            idMap.clear();
        }

    }

    private static Date nextWeekDate(Date date)
    {
        Calendar newDate = Calendar.getInstance(Locale.CHINA);
        newDate.setTime(date);
        newDate.add(Calendar.DATE, 7);
        return newDate.getTime();
    }

    private static Date beforeWeekDate(Date date)
    {
        Calendar newDate = Calendar.getInstance(Locale.CHINA);
        newDate.setTime(date);
        newDate.add(Calendar.DATE, 7);
        return newDate.getTime();
    }
}
